package com.lolaage.tracks.content;

import java.util.List;

import android.util.Log;

import com.lolaage.tracks.Track;
import com.lolaage.tracks.TrackPoint;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-9-10
 * @see : 轨迹数据的提供者
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class TrackProvider
{
    private static final String TAG = "TrackProvider";
    private int mClientId;
    private TracksDB tracksDB;
    private TrackPointsDB pointsDB;
    
    public TrackProvider(int clientId)
    {
        this.mClientId = clientId;
        tracksDB = new TracksDB();
        pointsDB = new TrackPointsDB();
    }
    
    /** 创建一个轨迹*/
    public Track newTrack()
    {
        return tracksDB.newTrack(mClientId);
    }
    
    /** 获取最新一个轨迹*/
    public Track getLastTrack()
    {
        return tracksDB.getLastTrack(mClientId);
    }
    
    /** 添加一个节点到指定轨迹中*/
    public boolean addPoint(Track track, TrackPoint point)
    {
        point.trackId = track._id;
        long pid = pointsDB.addPoint(point);
        if(pid > 0)
        {
            if(track.startPid == 0)
            {
                track.startPid = pid;
                track.startTime = point.time;
            }else
            {
                track.endPid = pid;
                track.endTime = point.time;
            }
            // 保存轨迹信息
            tracksDB.updateTrack(track);
            return true;
        }else
        {
            Log.e(TAG, "addPoint fail!");
            return false;
        }
    }
    
    /** 获取最后一个有效的节点*/
    public TrackPoint getLastPoint(long endPid)
    {
        return pointsDB.getPoint(endPid);
    }
    
    /** 获取指定轨迹中的节点列表*/
    public List<TrackPoint> getPoints(long trackId)
    {
        return pointsDB.getTrackPoints(trackId, -1, 0);
    }
    
    /** 获取轨迹列表*/
    public List<Track> getTrackList(int page, int num, boolean last)
    {
        return tracksDB.getTrackList(mClientId, page, num, last);
    }
    
    /** 删除轨迹*/
    public boolean deleteTrack(long trackId)
    {
        if( tracksDB.deleteTrack(trackId))
        {
            pointsDB.deletePoints(trackId);
            return true;
        }
        return false;
    }
}